<?php

class Rating
{

    protected static $_rating = array(
	1 => -1,
	2 => -0.5,
	3 => 0.5,
	4 => 0.75,
	5 => 1
    );

    public static function vote($model, $direction)
    {
	if (!$model || !$model->getDbData('user_id')) {
	    return false;
	}
	$currentUser = Yii::app()->user->getModel();
	$modelUser = FactoryService::get('user')->get($model->getDbData('user_id'));

	if (!$modelUser || !$currentUser) {
	    return false;
	}

	$karma = $currentUser->getDbData('karma');
	$minSize = 0.004;
	$maxSize = 0.5;
	$sizeRange = $maxSize - $minSize;
	$minCount = log(0 + 1);
	$maxCount = log(500 + 1);
	$countRange = $maxCount - $minCount;
	if ($countRange == 0) {
	    $countRange = 1;
	}
	if ($karma > 50 && $karma < 200) {
	    $rating = $karma / 70;
	}
	elseif ($karma >= 200) {
	    $rating = $karma / 10;
	}
	else {
	    $rating = $karma / 130;
	}
	$delta = $minSize + (log($rating + 1) - $minCount) * ($sizeRange / $countRange);

	$modelUser->karma += $direction * $delta;
	FactoryService::get('user')->save($modelUser);
    }

    public static function opinion(OpinionModel $model)
    {
	if (!$model->getDbData('target_type') || !$model->getDbData('target_id')) {
	    return false;
	}
	FactoryService::get('opinion')->getOpinionUser($model);
	$user = $model->getUser();
	if (!$user) {
	    return false;
	}

	$targetModel = FactoryService::get($model->getDbData('target_type'))->get($model->getDbData('target_id'));
	if (!$targetModel) {
	    return false;
	}	
	$karma = $user->getDbData('karma');
	$minSize = 0.004;
	$maxSize = 0.5;
	$sizeRange = $maxSize - $minSize;
	$minCount = log(0 + 1);
	$maxCount = log(500 + 1);
	$countRange = $maxCount - $minCount;
	if ($countRange == 0) {
	    $countRange = 1;
	}
	if ($karma > 50 && $karma < 200) {
	    $rating = $karma / 70;
	}
	elseif ($karma >= 200) {
	    $rating = $karma / 10;
	}
	else {
	    $rating = $karma / 130;
	}
	$delta = $minSize + (log($rating + 1) - $minCount) * ($sizeRange / $countRange);

	$targetModel->karma += self::$_rating[intval($model->getDbData('user_rating'))] * $delta;	
	FactoryService::get($model->getDbData('target_type'))->save($targetModel);
    }

}